package com.soloyogame.anitoys.business.web.controller.manage.news;


import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.soloyogame.anitoys.business.web.controller.BaseController;
import com.soloyogame.anitoys.business.web.controller.util.LoginUserHolder;
import com.soloyogame.anitoys.business.web.controller.util.RequestHolder;
import com.soloyogame.anitoys.db.bean.User;
import com.soloyogame.anitoys.db.commond.Catalog;
import com.soloyogame.anitoys.db.commond.News;
import com.soloyogame.anitoys.db.page.PagerModel;
import com.soloyogame.anitoys.service.CatalogService;
import com.soloyogame.anitoys.service.IndexImgService;
import com.soloyogame.anitoys.service.NewsService;


/**
 * 文章管理
 * @author huangf
 * @author dylan
 * 
 */
@Controller
@RequestMapping("/manage/news/")
public class NewsAction extends BaseController<News> 
{
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(NewsAction.class);
    private static final String page_toList = "/manage/news/newsList";
    private static final String page_toEdit = "/manage/news/newsEdit";
    private static final String page_toAdd = "/manage/news/newsEdit";
    private NewsAction() {
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }
    @Autowired
	private NewsService newsService;
    @Autowired
	private IndexImgService indexImgService;
    @Autowired
	private CatalogService catalogService;

//	private String type;//文章类型。通知：notice；帮助：help
	
	private List<News> news;// 门户新闻列表
	

	public CatalogService getCatalogService() {
		return catalogService;
	}

	public void setCatalogService(CatalogService catalogService) {
		this.catalogService = catalogService;
	}

    @Autowired
	public NewsService getService() {
		return newsService;
	}

	public void setNewsService(NewsService newsService) {
		this.newsService = newsService;
	}

	public IndexImgService getIndexImgService() {
		return indexImgService;
	}

	public void setIndexImgService(IndexImgService indexImgService) {
		this.indexImgService = indexImgService;
	}

	public List<News> getNews() {
		return news;
	}

	public void setNews(List<News> news) {
		this.news = news;
	}

	@Override
	public void insertAfter(News e) {
		e.clear();
	}
	
	/**
	 * 新增或者修改后文章的状态要重新设置为未审核状态
	 */
	@Override
    @RequestMapping(value = "insert", method = RequestMethod.POST)
	public String insert(HttpServletRequest request, News e, RedirectAttributes flushAttrs) throws Exception 
	{
		logger.error("NewsAction code = " + e.getCode());
		User user = LoginUserHolder.getLoginUser();
		e.setBusinessId(user.getBusinessId());
		e.setCreateAccount(user.getUsername());
		e.setStatus(News.news_status_n);//未审核
		
		getService().insert(e);
		return "redirect:toEdit2?id="+e.getId();
	}
	
	/**
	 * 修改文章
	 */
	@Override
    @RequestMapping(value = "update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, News e, RedirectAttributes flushAttrs) throws Exception 
	{
		logger.error("NewsAction code = ");
		logger.error("NewsAction code = " + e.getCode()+",id="+e.getId());
		getService().update(e);
		
		return "redirect:toEdit2?id="+e.getId();
	}
	
	//列表页面点击 编辑商品
    @RequestMapping(value = "toEdit")
	public String toEdit(News e, ModelMap model) throws Exception 
	{
//		getSession().setAttribute("insertOrUpdateMsg", "");
		return toEdit0(e, model);
	}
	
	/**
	 * 添加或编辑商品后程序回转编辑
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "toEdit2")
	public String toEdit2(News e, ModelMap model) throws Exception 
	{
		return toEdit0(e, model);
	}

    @RequestMapping(value = "toEdit0")
	private String toEdit0(News e, ModelMap model) throws Exception 
	{
        model.addAttribute("catalogsArticle", loadCatalogs2("a"));
		return super.toEdit(e, model);
	}
	
	/**
	 * 同步缓存内的新闻
	 * 审核通过，记录将会出现在门户上
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "updateStatusY", method = RequestMethod.POST)
	public String updateStatusY(String[] ids, String type, RedirectAttributes flushAttrs) throws Exception {
		newsService.updateStatus(ids,News.news_status_y);
		addMessage(flushAttrs, "操作成功!");
		return "redirect:selectList?type=" + type;
	}
	/**
	 * 审核未通过,记录将不会出现在门户上
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "updateStatusN", method = RequestMethod.POST)
	public String updateStatusN(String[] ids, String type, RedirectAttributes flushAttrs) throws Exception 
	{
		newsService.updateStatus(ids,News.news_status_n);
		addMessage(flushAttrs, "操作成功!");
		return "redirect:selectList?type=" + type;
	}

	/**
	 * 显示指定的文章
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "up")
	public String up(News e, RedirectAttributes flushAttrs) throws Exception 
	{
		return updateDownOrUp0(e, News.news_status_y, flushAttrs);
	}

	/**
	 * 不显示指定的文章
	 * @return
	 * @throws Exception
	 */
    @RequestMapping(value = "down")
	public String down(News e, RedirectAttributes flushAttrs) throws Exception 
	{
		return updateDownOrUp0(e, News.news_status_n, flushAttrs);
	}
	
	private String updateDownOrUp0(News e, String status, RedirectAttributes flushAttrs) throws Exception 
	{
		if(StringUtils.isBlank(e.getId()))
		{
			throw new NullPointerException("参数不能为空！");
		}
		
		News news = new News();
		news.setId(e.getId());
		news.setStatus(status);
		newsService.updateDownOrUp(news);
		addMessage(flushAttrs, "更新成功!");
		return "redirect:toEdit2?id="+e.getId();
	}
	
	/**
	 * 检查文章code的唯一性
	 * @return
	 * @throws IOException
	 */
    @RequestMapping(value = "unique")
    @ResponseBody
	public String unique(News e) throws IOException
	{
		
		logger.error("检查文章code的唯一性");
		if(StringUtils.isBlank(e.getCode()))
		{
			throw new NullPointerException("参数不能为空！");
		}
		
		int c = newsService.selectCount(e);
		if(StringUtils.isBlank(e.getId())){
			if(c==0){
				return "{\"ok\":\"文章code可以使用!\"}";
			}else{
				return "{\"error\":\"文章code已经被占用!\"}";
			}
		}else{
			News news = newsService.selectById(e.getId());
			if(news.getCode().equals(e.getCode()) || c==0){
				return "{\"ok\":\"文章code可以使用!\"}";
			}else{
				return "{\"error\":\"文章code已经被占用!\"}";
			}
		}
		
//		return null;
	}

	@Override
    @RequestMapping(value = "toAdd")
	public String toAdd(News e, ModelMap model) throws Exception {
		String type = e.getType();
		e.clear();
		e.setType(type);
        model.addAttribute("e", e);
        model.addAttribute("catalogsArticle", loadCatalogs2("a"));
		return page_toAdd;
	}
	
	@Override
	protected void selectListAfter(PagerModel pager) {
		pager.setPagerUrl("selectList");
        RequestHolder.getRequest().setAttribute("catalogsArticle", loadCatalogs2("a"));
	}
	
	/**
     * 公共的分页方法
     * @return
     * @throws Exception
     */
	@Override
    @RequestMapping("selectList")
    public String selectList(HttpServletRequest request, @ModelAttribute("e") News e) throws Exception 
    {
        /**
         * 由于prepare方法不具备一致性，加此代码解决init=y查询的时候条件不被清除干净的BUG
         */
        this.initPageSelect();
        setParamWhenInitQuery(e);

        int offset = 0;//分页偏移量
        if (request.getParameter("pager.offset") != null) 
        {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        if (offset < 0)
            offset = 0;
        e.setOffset(offset);
        User u = LoginUserHolder.getLoginUser();
        e.setBusinessId(u.getBusinessId());
        PagerModel pager = getService().selectPageList(e);
        if (pager == null) 
        {
            pager = new PagerModel();
        }
        // 计算总页数
        pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1)/ pager.getPageSize());
        pager.setPagerUrl("selectList");
        selectListAfter(pager);
        request.setAttribute("type", e.getType());
        request.setAttribute("pager", pager);
        return page_toList;
    }
	
	/**
     * 重写批量删除
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "deletesNews", method = RequestMethod.POST)
    public String deletesNews(HttpServletRequest request, String[] ids,String type, @ModelAttribute("e") News e, RedirectAttributes flushAttrs) throws Exception 
    {
        getService().deletes(ids);
        addMessage(flushAttrs, "操作成功！");
        return "redirect:selectList?type=" + type;
    }
    
    /**
  	 * 原来递归的方式修改为非递归方式。
  	 * 非递归方法查询商品/文章目录结构，并且自动排序。
  	 * @param type
  	 */
  	private List<Catalog> loadCatalogs2(String type){
          List<Catalog> catalogs = Lists.newLinkedList();
  		Catalog cc = new Catalog();
  		cc.setType(type);
  		List<Catalog> catalogsList = catalogService.selectList(cc);
  		if(catalogsList!=null){

  			Map<String, Catalog> map = new HashMap<String, Catalog>();
  			for(Iterator<Catalog> it = catalogsList.iterator();it.hasNext();){
  				Catalog item = it.next();

  				if(StringUtils.isNotBlank(item.getPid()) && item.getPid().equals("0")){
  					//是否在导航栏显示中文化
  					if(item.getShowInNav().equals(Catalog.catalog_showInNav_y)){
  						item.setShowInNavStr("是");
  					}

  					map.put(item.getId(), item);
  					it.remove();
  				}
  			}

  			for(Iterator<Catalog> it = catalogsList.iterator();it.hasNext();){
  				Catalog item = it.next();
  				if(StringUtils.isNotBlank(item.getPid())){
//  							list.add(item);
  					Catalog rootItem = map.get(item.getPid());
  					if(rootItem!=null){
  						if(rootItem.getChildren()==null){
  							rootItem.setChildren(new LinkedList<Catalog>());
  						}
  						rootItem.getChildren().add(item);
  					}
  					it.remove();
  				}
  			}

  			for(Iterator<Entry<String, Catalog>> it = map.entrySet().iterator();it.hasNext();){
  				catalogs.add(it.next().getValue());
  			}

  			//对主类别和子类别进行排序
  			Collections.sort(catalogs, new Comparator<Catalog>() {
  				public int compare(Catalog o1, Catalog o2) {
  					if (o1.getOrder1() > o2.getOrder1()) {
  						return 1;
  					} else if (o1.getOrder1() < o2.getOrder1()) {
  						return -1;
  					}
  					return 0;
  				}
  			});

  			for(int i=0;i<catalogs.size();i++){
  				if(catalogs.get(i).getChildren()==null){
  					continue;
  				}
  				Collections.sort(catalogs.get(i).getChildren(), new Comparator<Catalog>() {
  					public int compare(Catalog o1, Catalog o2) {
  						if (o1.getOrder1() > o2.getOrder1()) {
  							return 1;
  						} else if (o1.getOrder1() < o2.getOrder1()) {
  							return -1;
  						}
  						return 0;
  					}
  				});
  			}
  		}
          return catalogs;
  	}
	
	
}
